import aplpy
print(aplpy.version.version)
import numpy as np
import pylab as P
import matplotlib.pyplot as mpl
import math
import sys
#from readcol import *
#from tycholib import *
import os
#import ds9cmap
#import viridis
from astropy import wcs
from astropy.io import fits
import cmocean as cmo

print(len(sys.argv))
if len(sys.argv) != 36:  # the program name and the two arguments
  # stop the program and print an error message
  sys.exit("python images-1panel.py filename outfilename ra dec minpixval maxpixval separation size(arcsec) scalebar(arcsec) distance name")

image = str(sys.argv[1])
outfilename=str(sys.argv[2])
ra = float(sys.argv[3])
dec = float(sys.argv[4])
minpixval = float(sys.argv[5])
maxpixval = float(sys.argv[6])
size = float(sys.argv[7])
scalebar = float(sys.argv[8])
distance=float(sys.argv[9])
name=str(sys.argv[10])
pa=float(sys.argv[11])
showoutflow=str(sys.argv[12])
sigma=float(sys.argv[13])
showcontours=str(sys.argv[14])
showsources=str(sys.argv[15])
imagestretch=str(sys.argv[16])
redimage=str(sys.argv[17])
redstart=float(sys.argv[18])
redinterval=float(sys.argv[19])
rednoise=float(sys.argv[20])
showredimage=str(sys.argv[21])
colororgray=str(sys.argv[22])
colormap=str(sys.argv[23])
plotlabel=str(sys.argv[24])
textcolor=str(sys.argv[25])
delta_x=float(sys.argv[26])/3600.0
delta_y=float(sys.argv[27])/3600.0
sourcecolor=str(sys.argv[28])
contourcolor=str(sys.argv[29])
s2ndbeammaj=float(sys.argv[30])
s2ndbeammin=float(sys.argv[31])
s2ndbeampa=float(sys.argv[32])
show2ndbeam=str(sys.argv[33])
excludepiximage=str(sys.argv[34])
showexcludepix=str(sys.argv[35])



def fix_aplpy_fits(aplpy_obj, dropaxis=2):
    """This removes the degenerated dimensions in APLpy 2.X...
    The input must be the object returned by aplpy.FITSFigure().
    `dropaxis` is the index where to start dropping the axis (by default it assumes the 3rd,4th place).
    """
    temp_wcs = aplpy_obj._wcs.dropaxis(dropaxis)
    temp_wcs = temp_wcs.dropaxis(dropaxis)
    aplpy_obj._wcs = temp_wcs

def standardStuff():
   gc1.axis_labels.set_font(size='x-large')
   gc1.tick_labels.set_style('colons')
   gc1.tick_labels.set_xformat('hh:mm:ss.ss')
   gc1.tick_labels.set_yformat('dd:mm:ss.s')
   gc1.tick_labels.set_font(size='medium')
   gc1.ticks.set_color('black')
   gc1.ticks.show()
   if '2.0.' in aplpy.version.version:
      print('')
      gc1.axis_labels.set_ypad(-1)
   else:
      gc1.axis_labels.set_ypad(10)

   #gc1.tick_labels.hide()
   #gc1.ticks.hide()

   gc1.add_scalebar(scalebar/3600.0,color=textcolor)
   gc1.scalebar.set_corner('bottom left')
   gc1.scalebar.set_label(str(scalebar)+'" ('+str(int(scalebar*distance))+' au)')
   gc1.scalebar.set_linewidth(6)
   gc1.scalebar.set_font_size('xx-large')

   gc1.add_beam()
   gc1.beam.set_corner('bottom right')
   gc1.beam.set_color('orange')
   gc1.beam.set_hatch('+')

def drawOutflow():
   dxred=0.0
   dyred=0.0
   dxblue=0.0
   dyblue=0.0
   length=size/8.0/3600.0
   if size > 5.0:
      length=size/8.0/3600.0
   else:
      length=size/4.0/3600.0

   if pa > 180.0:
     panew=pa-180.0 
   else:
     panew=pa
   angle=abs(abs(panew)-90.0)
   xlength=length*math.cos(angle*3.14/180.0)
   ylength=length*math.sin(angle*3.14/180.0)
  
   xpt1=xlength
   ypt1=ylength
   xpt2=-xlength
   ypt2=-ylength

   if pa == 180.0 or pa == 360.0:
      dxred=0.0
      dxblue=0.0
   if pa == 90.0 or pa == 270.0:
      dyred=0.0 
      dyblue=0.0
   if pa > 180.0 and pa <= 270.0:
      dxblue=xpt2
      dyblue=ypt2
      dxred=xpt1 
      dyred=ypt1
   if pa > 180.0 and pa > 270.0:
      dxblue=xpt2
      dyblue=ypt1
      dxred=xpt1
      dyred=ypt2
   if pa < 180.0 and pa > 90.0:
      dxblue=xpt1
      dyblue=ypt2
      dxred=xpt2
      dyred=ypt1
   if pa < 180.0 and pa <=90.0:
      dxblue=xpt1
      dyblue=ypt1
      dxred=xpt2
      dyred=ypt2
   print(dxblue*3600.0,dyblue*3600.0,dxred*3600.0,dyred*3600.0)
#   gc1.show_arrows(ra+dxblue/4.0,dec+dyblue/4.0, dxblue, dyblue, color='cyan')
#   gc1.show_arrows(ra+dxred/4.0,dec+dyred/4.0, dxred, dyred, color='red')

   if size > 5.0:
      ranew=ra-size/6.0/3600.0
      decnew=dec-size/6.0/3600.0
   else:
      ranew=ra-size/3.0/3600.0
      decnew=dec-size/3.0/3600.0
   gc1.show_arrows(ranew,decnew, dxblue, dyblue, color='blue')
   gc1.show_arrows(ranew,decnew, dxred, dyred, color='red')

def drawContours(contstart=None,continterval=None,contnoise=None):
   contours1=np.arange(contstart,contstart*10,continterval,dtype='float32')
   contours2=np.arange(contstart*10,contstart*100.0,continterval*5.0,dtype='float32')
   contours3=np.arange(contstart*30.0,contstart*100.0,continterval*10.0,dtype='float32')
   poscontours=np.concatenate((contours1,contours2)) #,contours3))
   poscontours=np.linspace(np.log10(contstart*contnoise),np.log10(contnoise*500.0),num=1)  #5 is good too!
   poscontours=10**poscontours
   negcontours=poscontours[::-1]*(-1.0)
   contours=np.concatenate((negcontours,poscontours))
   #print(contours)
   return contours

fig = mpl.figure(figsize=(6.5,5.5))

dx=0.0
dy=0.0
#os.system('rm -rf '+ image+'cut.fits')
#fitscut2d(image,image+'cut.fits',ra,dec,300)
#image=image+'cut.fits'

print(name, image, ra,dec)
gc1 = aplpy.FITSFigure(image, figure=fig, subplot=[0.15+dx,0.1+dy,0.75,0.8182])
if ('2.0.' in aplpy.version.version) and (len(gc1._wcs.array_shape) > 2):
   fix_aplpy_fits(gc1)
if colororgray == 'color':
   gc1.show_colorscale(vmin=minpixval,vmid=maxpixval/100.0,vmax=maxpixval,stretch=imagestretch,cmap=colormap)
if colororgray == 'gray':
   gc1.show_grayscale(vmin=minpixval,vmax=maxpixval,stretch=imagestretch,invert=True)

gc1.recenter(ra,dec,width=(size/3600.0),height=(size/3600.0))
#m0= minpixval*1000.0           # colorbar min value
#m4= maxpixval*1000.0             # colorbar max value
#num_ticks = 5
# to get ticks
#ticks = np.linspace(m0, m4, num_ticks)
# get labels
#ticklabels = np.linspace(m0, m4, num_ticks)
if '2.0.' in aplpy.version.version:
   gc1.add_colorbar(log_format=False)
   gc1.colorbar.set_font(size='medium')
else:
   gc1.show_colorbar(log_format=False)

gc1.colorbar.set_axis_label_text('Flux (Jy/beam km/s)')
gc1.colorbar.set_axis_label_font(size='medium')
'''
if showsources == 'y':
   sourcename,ra_src,dra_junk,dec_src,ddec_junk,freq9_junk,intflux9_junk,eintflux9_junk,pflux9_junk,rms9_junk,bmaj,bmin,gauss_pa,e_bmaj,e_bmin,e_pa,decon_bmaj,decon_bmin,decon_pa,e_decon_bmaj,e_decon_bmin,e_decon_pa=readcol('ALMAOrion-all+VLA.cat',twod=False,skipline=1)
   gc1.show_markers(ra_src[:]+delta_x,dec_src[:]+delta_y,c=sourcecolor,marker='+',zorder=20)
   #gc1.add_label(ra_src[:]+delta_x,dec_src[:]+delta_y, sourcename[:], relative=False,size='large',color='white',weight='heavy')
   n_sources=sourcename.shape[0]
   for i in range(0,n_sources):
      if sourcename[i] =='FIR4-D' or sourcename[i] =='HOPS-368' or sourcename[i] =='HOPS-66-A' or sourcename[i] == 'HOPS-66-B':
         gc1.add_label(ra_src[i]+(size/3600.0*0.11),dec_src[i],sourcename[i],color=sourcecolor)
      else:
         gc1.add_label(ra_src[i]-(size/3600.0*0.12),dec_src[i],sourcename[i],color=sourcecolor)
'''
gc1.show_markers(84.5754276-0.03/3600.0,-7.0405608+0.03/3600.0,c='white',marker='+',zorder=20,s=40)
gc1.show_ellipses(84.5754276-0.03/3600.0,-7.0405608+0.03/3600.0,0.2/3600.0,0.16/3600.0,135.0,edgecolor='gray',linestyle='--',lw=2.0)
gc1.add_label(0.5, 0.95, name, relative=True,size='x-large',color=textcolor,weight='heavy')
gc1.add_label(0.1, 0.95, plotlabel, relative=True,size='x-large',color=textcolor,weight='heavy')
#gc1.add_label(0.5, 0.875, r'$\Delta$'+separation, relative=True,size='large',color='white',weight='heavy')

standardStuff()

if showredimage == 'y':
   contours=drawContours(redstart,redinterval,rednoise)
   gc1.show_contour(redimage,levels=contours,colors=contourcolor,linewidths=1.0)

if showexcludepix == 'y':
   gc1.show_contour(excludepiximage,levels=np.array([0.00001]),colors='white',linewidths=1.0,linestyles='dotted')


if pa < 360.0 and showoutflow == 'y':
   drawOutflow()

if show2ndbeam == 'y':
   print(s2ndbeammaj,s2ndbeammin,s2ndbeampa)
   gc1.show_ellipses(ra-(size/3)/3600.0,dec-(size/2.4)/3600.0,s2ndbeammaj,s2ndbeammin,90.0+s2ndbeampa,facecolor=contourcolor,edgecolor=contourcolor)

gc1.list_layers()
#os.system('rm -rf '+ image)
#os.system('rm -rf '+ redimage)
#os.system('rm -rf '+ blueimage)

fig.savefig(outfilename,dpi=200)
fig.savefig(outfilename.replace('pdf','png'),dpi=200)
